'use client';

import React, { useEffect, useState } from 'react';
import { ToastContainer, toast } from 'react-toastify';
import type { ToastOptions } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

type MessageType = 'success' | 'error' | 'warning' | 'info';

const defaultOptions: ToastOptions = {
  position: 'top-right',
  autoClose: 3000, // 增加显示时间，让用户有更多时间看到消息
  hideProgressBar: false,
  closeOnClick: true,
  pauseOnHover: true,
  draggable: true,
  progress: undefined,
  theme: 'light',
};

const showMessage = (type: MessageType, message: string | Error | unknown, options: Partial<ToastOptions> = {}) => {
  // 确保消息是字符串类型
  const safeMessage = typeof message === 'string' ? message : 
                     message instanceof Error ? message.message : 
                     '操作完成';
  
  const toastOptions = { ...defaultOptions, ...options };
  
  try {
    switch (type) {
      case 'success':
        toast.success(safeMessage, toastOptions);
        break;
      case 'error':
        toast.error(safeMessage, toastOptions);
        break;
      case 'warning':
        toast.warn(safeMessage, toastOptions);
        break;
      case 'info':
      default:
        toast.info(safeMessage, toastOptions);
        break;
    }
  } catch (error) {
    console.error('显示消息通知失败:', error);
  }
};

// 由于某些页面（如 ComplianceView）也会渲染 MessageTip，导致出现多个 ToastContainer，
// 在高频调用 toast.dismiss 时 React-Toastify 内部可能找不到对应实例而抛出
// "cannot access property \"removalReason\", c.get(...) is undefined"。
// 通过全局布尔值保证同一时刻只渲染一个 ToastContainer。
let hasToastContainer = false;

const MessageTip: React.FC = () => {
  const [shouldRender, setShouldRender] = useState(false);

  useEffect(() => {
    if (!hasToastContainer) {
      setShouldRender(true);
      hasToastContainer = true;
    }
    // 卸载时释放占用，防止热重载等场景下无法再次挂载
    return () => {
      if (shouldRender) {
        hasToastContainer = false;
      }
    };
  }, [shouldRender]);

  // 使用默认配置创建 ToastContainer，确保在所有页面都能正常显示
  return shouldRender ? (
    <ToastContainer
      position="top-right"
      autoClose={3000}
      hideProgressBar={false}
      newestOnTop
      closeOnClick
      rtl={false}
      pauseOnFocusLoss
      draggable
      pauseOnHover
    />
  ) : null;
};

export { MessageTip, showMessage };
